package com.ddddddl.zhangben;

import java.util.HashMap;
import java.util.Map.Entry;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import com.ddddddl.zhangben.logic.AccountLogic;
import com.ddddddl.zhangben.logic.ExecuteMessage;

import android.graphics.Color;
import android.os.Bundle;

public class StatActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		listen(AccountLogic.getInstance(), AccountLogic.NOTIFY_AMOUNT_INIT, AccountLogic.NOTIFY_AMOUNT_UPDATE);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onNotify(ExecuteMessage message) {
		super.onNotify(message);
		switch (message.type) {
		case AccountLogic.NOTIFY_AMOUNT_INIT:
		case AccountLogic.NOTIFY_AMOUNT_UPDATE:
			HashMap<Long, Double> amountMap = (HashMap<Long, Double>) message.get(AccountLogic.PARAM_AMOUNT_MAP);
			int[] colorsData = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA, Color.YELLOW, Color.CYAN };
			int size = amountMap.size();
			double[] values = new double[size];
			int[] colors = new int[size]; 
			String[] typeNames = new String[size];
			int index = 0;
			for (Entry<Long, Double> entry : amountMap.entrySet()) {
				values[index] = entry.getValue();
				colors[index] = colorsData[index];
 				typeNames[index] = AccountLogic.getInstance().getType(entry.getKey()).name;
				index++;
			}
			
			DefaultRenderer renderer = buildCategoryRenderer(colors);
			renderer.setZoomButtonsVisible(true);
			renderer.setZoomEnabled(false);
			renderer.setChartTitleTextSize(20);
			renderer.setPanEnabled(false);
			renderer.setInScroll(true);
			GraphicalView pieChartView = ChartFactory.getPieChartView(this, buildCategoryDataset("Project budget", values, typeNames), renderer);
			pieChartView.setBackgroundResource(R.color.white);
			setContentView(pieChartView);
			break;

		default:
			break;
		}
	}

	protected DefaultRenderer buildCategoryRenderer(int[] colors) {
		DefaultRenderer renderer = new DefaultRenderer();
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setMargins(new int[] { 20, 30, 15, 0 });
		for (int color : colors) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(color);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	protected CategorySeries buildCategoryDataset(String title, double[] values, String[] typeNames) {
		CategorySeries series = new CategorySeries(title);
		int k = 0;
		for (double value : values) {
			series.add(typeNames[k++], value);
		}

		return series;
	}
	
	
}
